import axios from 'axios'
import ErrorHandler from './ErrorHandler'
const CancelToken = axios.CancelToken
class HttpRequest {
  constructor (baseURL) {
    this.baseURL = baseURL
    this.pending = {}
  }

  // 获取配置
  getInsideConfig () {
    const config = {
      baseURL: this.baseURL,
      headers: {
        'Content-Type': 'application/json;charset=utf-8'
      },
      timeout: 10000// 10S
    }
    return config
  }

  removePending (key, isRequest = false) {
    if (this.pending[key] && isRequest) {
      this.pending[key]('不要重复点击')
    }
    delete this.pending[key]
  }

  // 设定拦截器
  interceptors (instance) {
    // 请求拦截器:客户端->服务端
    instance.interceptors.request.use((config) => {
      // console.log('config is', config)
      const key = config.url + '&' + config.method
      // console.log(key)
      this.removePending(key, true)
      config.cancelToken = new CancelToken((c) => {
        this.pending[key] = c
      })
      return config
    }, (err) => {
      ErrorHandler(err)
      return Promise.reject(err)
    })

    // 响应请求:客户端<-服务端
    instance.interceptors.response.use((res) => {
      // console.log('res is', res)
      const key = res.config.url + '&' + res.config.method
      this.removePending(key)
      if (res.status === 200) {
        return Promise.resolve(res.data)
      } else {
        return Promise.reject(res)
      }
    }, (err) => {
      ErrorHandler(err)
      return Promise.reject(err)
    })
  }

  // 创建实例
  request (options) {
    const instance = axios.create()// 创建axios
    const newOptions = Object.assign(this.getInsideConfig(), options)// 配置
    this.interceptors(instance)// 拦截器
    return instance.request(newOptions)
  }

  // get
  get (url, config) {
    const options = Object.assign({
      method: 'get',
      url: url
    }, config)
    return this.request(options)
  }

  // post
  post (url, data) {
    return this.request({
      method: 'post',
      url: url,
      data: data
    })
  }
}

export default HttpRequest
